import { instantiate, Node, NodePool, Prefab, _decorator } from "cc";
const { ccclass, property } = _decorator;
/** 
  周无邪出品
  本源码用于学习研究使用。
  作者联系方式：tuya7078（微信）。
 */
@ccclass("poolManager")
export class poolManager {

    //白名单 不删除的对象池
    private whiteList_pool = {
        //值是资源路径 不做任何意义 只看key
        fabu_item: "item/fabu_item",
        tujian_item: "item/tujian_item",
        paysell_item: "item/paysell_item",
        self_paysell_item: "item/self_paysell_item"
    }
    private _dictPool: any = {}
    private _dictPrefab: any = {}

    static _instance: poolManager;


    static get instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new poolManager();
        return this._instance;
    }

    /**
     * 根据预设从对象池中获取对应节点
     */
    public getNode(prefab: Prefab, parent: Node) {
        if(!prefab){
        
            
            return
        }
        let name = prefab.name;
        //@ts-ignore
        if (!prefab.position) {
            //@ts-ignore
            name = prefab.data.name;
        }

        this._dictPrefab[name] = prefab;
        let node = null;
        if (this._dictPool.hasOwnProperty(name)) {
            //已有对应的对象池
            let pool = this._dictPool[name];
            if (pool.size() > 0) {
               // console.log("pool重节点池里拿出的", name);
                node = pool.get();
            } else {
               // console.log("实例化的-----", name);
                node = instantiate(prefab);
            }
        } else {
         // console.log("pool新创建的", name);
            //没有对应对象池，创建他！
            let pool = new NodePool();
            this._dictPool[name] = pool;

            node = instantiate(prefab);
        }

        node.parent = parent;
        node.active = true;
        return node;
    }

    /**
     * 将对应节点放回对象池中
     */
    public putNode(node: Node) {
        if (!node) {
            return;
        }
        let name = node.name;
        let pool = null;
        if (this._dictPool.hasOwnProperty(name)) {
            //已有对应的对象池
            pool = this._dictPool[name];
        } else {
            //没有对应对象池，创建他！
            pool = new NodePool();
            this._dictPool[name] = pool;
        }

        pool.put(node);
    }


    public getName() {
       // console.log("对象池：", this._dictPool, this._dictPrefab);

    }
    /**
     * 根据名称，清除对应对象池
     */
    public clearPool(name: string) {
        if (this._dictPool.hasOwnProperty(name)) {
            let pool = this._dictPool[name];
            pool.clear();
        }
    }

    /**
 * 根据名称，清除对应对象池
 */
    public clearAllPool() {
        for (let key in this._dictPool) {
            if (this.whiteList_pool.hasOwnProperty(key)) {
              //  console.log("白名单里的：", key);

                continue
            }
            this._dictPool[key].clear()
        }

    }

    // update (deltaTime: number) {
  
    // }
}
